package com.example.demoapi.api.aop;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demoapi.api.mapper.DetailsMapper;
import com.example.demoapi.api.mapper.OrderMapper;
import com.example.demoapi.api.pojo.Details;
import com.example.demoapi.api.pojo.Orders;
import com.example.demoapi.api.pojo.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author Hu
 * @date 2023/2/6
 * @apiNote
 */
@Component
@Aspect
public class UserBalanceChangeLog {
    /**
     * 用户金额的变动都要被此通知拦截，每一次金额的变动都将关联一个订单。
     * 用户金额变动api的请求最少需要传递两个信息用户id和订单id
     */
    private static final String MARK = "operation-user-balance/";

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private DetailsMapper detailsMapper;

    @Pointcut(value = "@within(UserBalanceLog)")
    public void transactionalPointCut() {
    }

    @Around("transactionalPointCut()")
    public Object log(ProceedingJoinPoint proceedingJoinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String[] split = request.getRequestURL().toString().split(MARK);
        Object[] args = proceedingJoinPoint.getArgs();
        Result result = null;
        try {
            result = (Result) proceedingJoinPoint.proceed(args);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        if (split != null && split.length > 1 && result != null && result.getCode() == 200) {
            String[] split1 = split[1].split("/");
            if (split1 != null && args.length > 1) {
                Details details = new Details();
                Orders orders = orderMapper.selectOne(new QueryWrapper<Orders>().eq("order_id", args[1]));
                details.setAmount(orders.getOrderAmount());
                details.setUserId(((Integer) args[0]).longValue());
                details.setOrderId(orders.getOrderId());
                details.setInfo(split1[0]);
                details.setDetailsId(System.currentTimeMillis());
                details.setCreateTime(new Date());
                details.setEndTime(new Date());
                detailsMapper.insert(details);
            }
        }
        return result;
    }
}
